<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { ElSelect, ElOption, ElMessage } from 'element-plus'
import { apiRequest } from '../utils/apiRequest'

// 定义props
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  },
  placeholder: {
    type: String,
    default: '请选择供应商'
  },
  disabled: {
    type: Boolean,
    default: false
  },
  clearable: {
    type: Boolean,
    default: true
  },
  filterable: {
    type: Boolean,
    default: true
  }
})

// 定义emits
const emit = defineEmits(['update:modelValue', 'change'])

// 供应商列表
const suppliers = ref([])
const loading = ref(false)
const currentValue = ref(props.modelValue)

// 监听外部value变化
watch(
  () => props.modelValue,
  (newValue) => {
    currentValue.value = newValue
  }
)

// 监听内部value变化并通知父组件
watch(
  currentValue,
  (newValue) => {
    emit('update:modelValue', newValue)
  }
)

// 获取供应商列表
const fetchSuppliers = async () => {
  loading.value = true
  try {
    const response = await apiRequest.get('/api/suppliers', {
      params: {
        page: 1,
        pageSize: 100
      }
    })
    
    // 处理不同格式的响应
    let suppliersData = []
    if (response?.items && response?.total) {
      // 分页格式响应
      suppliersData = response.items?.$values || response.items || []
    } else if (response?.$values) {
      // 带有$values属性的响应
      suppliersData = response.$values || []
    } else if (Array.isArray(response)) {
      // 直接返回数组
      suppliersData = response
    } else {
      // 默认处理
      suppliersData = []
    }
    
    suppliers.value = suppliersData
    
    // 检查是否有数据
    if (suppliers.value.length === 0) {
      ElMessage.info('没有找到供应商数据，请先创建供应商')
    }
  } catch (error) {
    const errorMsg = error.response?.data?.message || '获取供应商列表失败'
    ElMessage.error(errorMsg)
    console.error('Failed to get suppliers:', error)
  } finally {
    loading.value = false
  }
}

// 处理选择变化
const handleChange = (value: string) => {
  currentValue.value = value
  emit('change', value)
}

// 组件加载时获取供应商数据
onMounted(() => {
  fetchSuppliers()
})
</script>

<template>
  <ElSelect
    v-model="currentValue"
    :placeholder="placeholder"
    :disabled="disabled"
    :clearable="clearable"
    :filterable="filterable"
    :loading="loading"
    @change="handleChange"
    value-key="id"
    :key="currentValue || 'supplier-select'"
    :label="(item) => item?.supplierName || ''"
  >
    <ElOption
      v-for="supplier in suppliers"
      :key="supplier.id"
      :label="supplier.supplierName"
      :value="supplier.id.toString()"
    />
  </ElSelect>
</template>